# -*- encoding: UTF-8 -*-
import os
import os.path
from mod_python import util
from subprocess import Popen

N900REPLAY_HOME = "/home/thierry/Vidéos/n900"

def remove_queue(req,file=None):  
  list = os.listdir(N900REPLAY_HOME)  
  for f in list:
    if f.endswith(".ts"):
      if file:
         if unicode(file,'latin-1')==unicode(f,'utf'): 
           os.remove(os.path.join(N900REPLAY_HOME, f))
      else:
            os.remove(os.path.join(N900REPLAY_HOME, f))

  util.redirect(req,"../queue.psp")

def remove_converted(req, file=None):
  list = os.listdir("/home/thierry/Vidéos/n900/converted")
  for f in list:
    if f.endswith(".mp4"):
      if file:
        if unicode(file,'latin-1')==unicode(f,'utf'):
          os.remove("/home/thierry/Vidéos/n900/converted/" + f)
      else:
        os.remove("/home/thierry/Vidéos/n900/converted/" + f)

  util.redirect(req,"../converted.psp")

def remove_backup(req,file=None):
  list = os.listdir("/home/thierry/Vidéos/n900/backup")
  for f in list:
    if f.endswith(".ts"):
      if file:
        if unicode(file,'latin-1')==unicode(f,'utf'):
          os.remove("/home/thierry/Vidéos/n900/backup/" + f)
      else:
        os.remove("/home/thierry/Vidéos/n900/backup/" + f)

  util.redirect(req,"../download.psp")

def start(req,action):
  if action == "download":
    p = Popen("/home/thierry/Vidéos/n900/backup/download.sh", cwd="/home/thierry/Vidéos/n900/backup")        
    util.redirect(req,"../download.psp")
  elif action == "convert":
    p = Popen("/home/thierry/Vidéos/n900/convert_all.sh", cwd="/home/thierry/Vidéos/n900")        
    util.redirect(req,"../converted.psp")
  else:
    util.redirect(req,"../index.psp")

def stop(req,action):
  if action == "download":           
    util.redirect(req,"../download.psp")
  elif action == "convert":         
    util.redirect(req,"../converted.psp")
  else:
    util.redirect(req,"../index.psp")

def reset(req,action):
  if action == "download":         
    files_to_clean = ["/home/thierry/Vidéos/n900/backup/.listing2.txt","/home/thierry/Vidéos/n900/backup/.listing1.txt","/home/thierry/Vidéos/n900/backup/.lock"]
    for f in files_to_clean:
      if os.path.isfile(f):
        os.remove(f)
    util.redirect(req,"../download.psp")
  elif action == "convert":     
    files_to_clean = ["/home/thierry/Vidéos/n900/.lock", "/home/thierry/Vidéos/n900/.work_in_progress", "/home/thierry/Vidéos/n900/.work_pid"]
    for f in files_to_clean:
      if os.path.isfile(f):
        os.remove(f)
    util.redirect(req,"../converted.psp")
  else:
    util.redirect(req,"../index.psp")

